package com.markus.spring.ioc.dependency.lookup;

import com.markus.spring.ioc.dependency.annotation.Super;
import com.markus.spring.ioc.dependency.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * Date:Create in 2021/2/2 20:58
 * 通过 Bean 名称进行查找
 * @author markusZhang
 */
public class DependencyLookUpDemo {
    public static void main(String[] args) {
        //1.配置 xml 文件
        //2.启动 Spring 应用上下文
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/context-dependency-lookup.xml");
        // 根据类型 实时查找 查找单个
//        lookUpByType(beanFactory);
//        // 根据类型 集合实例
//        lookUpCollectionByType(beanFactory);
//        // 根据注解 查找Bean
        lookUpByAnnotation(beanFactory);


        // 实时查找
//        lookUpInRealTime(beanFactory);
        // 延迟查找
//        lookUpInLazy(beanFactory);
    }

    private static void lookUpByAnnotation(BeanFactory beanFactory){
        if (beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, Object> beansWithAnnotation = listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println(beansWithAnnotation);
        }
    }

    private static void lookUpCollectionByType(BeanFactory beanFactory){
        if (beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有 User 集合对象："+beansOfType);
        }
    }

    private static void lookUpByType(BeanFactory beanFactory){
        User bean = beanFactory.getBean(User.class);
        System.out.println("实时查找："+bean);
    }

    private static void lookUpInLazy(BeanFactory beanFactory){
        ObjectFactory<User> objectFactory = (ObjectFactory) beanFactory.getBean("objectFactory");
        User object = objectFactory.getObject();
        System.out.println("延迟查找："+object);
    }

    private static void lookUpInRealTime(BeanFactory beanFactory) {
        User user = (User) beanFactory.getBean("user");
        System.out.println("实时查找："+user);
    }
}
